<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="600px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-tabs>
        <el-tab-pane label="基本信息">
          <el-form-item label="公司名称" prop="companyName">
            <el-input v-model="formData.companyName" placeholder="请输入公司名称" />
          </el-form-item>
          <el-form-item label="用户ID" prop="userId">
            <el-input v-model="formData.userId" placeholder="请输入用户ID" />
          </el-form-item>
          <el-form-item label="法人姓名" prop="legalName">
            <el-input v-model="formData.legalName" placeholder="请输入法人姓名" />
          </el-form-item>
          <el-form-item label="法人手机" prop="legalPhone">
            <el-input v-model="formData.legalPhone" placeholder="请输入手机号" />
          </el-form-item>
          
          <!-- 银行信息 -->
          <el-divider>银行信息</el-divider>
          <el-form-item label="开户行">
            <el-input v-model="formData.bankName" placeholder="请输入开户行" />
          </el-form-item>
          <el-form-item label="开户名">
            <el-input v-model="formData.bankAccountName" placeholder="请输入开户名" />
          </el-form-item>
          <el-form-item label="银行账号" prop="bankAccount">
            <el-input v-model="formData.bankAccount" placeholder="请输入银行账号" />
          </el-form-item>
          
          <!-- 价格信息 -->
          <el-divider>价格信息</el-divider>
          <el-form-item label="价格类型" prop="priceType">
            <el-radio-group v-model="formData.priceType">
              <el-radio :label="1">固定单价</el-radio>
              <el-radio :label="2">浮动单价</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <el-form-item v-if="formData.priceType === 1" label="固定单价" prop="fixedPrice">
            <el-input-number 
              v-model="formData.fixedPrice" 
              :precision="2" 
              :step="0.1" 
              :min="0"
              placeholder="请输入固定单价（元/条）"
              class="!w-full"
            />
          </el-form-item>
          
          <el-form-item v-if="formData.priceType === 2" label="浮动单价下限" prop="minPrice">
            <el-input-number 
              v-model="formData.minPrice" 
              :precision="2" 
              :step="0.1" 
              :min="0"
              placeholder="请输入浮动单价下限（元/条）"
              class="!w-full"
            />
          </el-form-item>
          
          <el-form-item v-if="formData.priceType === 2" label="浮动单价上限" prop="maxPrice">
            <el-input-number 
              v-model="formData.maxPrice" 
              :precision="2" 
              :step="0.1" 
              :min="0"
              placeholder="请输入浮动单价上限（元/条）"
              class="!w-full"
            />
          </el-form-item>
          
          <el-form-item label="每日数据限制" prop="dailyDataLimit">
            <el-input-number 
              v-model="formData.dailyDataLimit" 
              :min="0" 
              :step="10"
              placeholder="请输入每日数据提取限制（0表示无限制）"
              class="!w-full"
            />
          </el-form-item>
          
          <!-- 认证状态-->
          <el-divider>认证状态</el-divider>
          <el-form-item label="认证状态" prop="status">
            <el-radio-group v-model="formData.status">
              <el-radio :label="0">待审核</el-radio>
              <el-radio :label="1">已认证</el-radio>
              <el-radio :label="2">未通过</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <el-form-item label="审核备注" prop="auditRemark">
            <el-input 
              v-model="formData.auditRemark" 
              type="textarea" 
              :rows="3"
              placeholder="请输入审核备注"
            />
          </el-form-item>
          
          <el-form-item label="认证通过时间" prop="authTime" v-if="formData.status === 1">
            <el-date-picker
              v-model="formData.authTime"
              type="datetime"
              value-format="x"
              placeholder="选择认证通过时间"
            />
          </el-form-item>
        </el-tab-pane>
        
        <el-tab-pane label="证件信息">
          <div class="grid grid-cols-1 gap-4">
            <div>
              <div class="mb-2 font-bold">营业执照</div>
              <el-form-item prop="businessLicense">
                <el-input v-model="formData.businessLicense" placeholder="请输入营业执照URL">
                  <template #append>
                    <el-button @click="previewImage(formData.businessLicense)">预览</el-button>
                  </template>
                </el-input>
                <el-image
                  v-if="formData.businessLicense"
                  :src="formData.businessLicense"
                  :preview-src-list="[formData.businessLicense]"
                  fit="contain"
                  style="width: 100%; max-height: 200px; margin-top: 8px;"
                />
              </el-form-item>
            </div>
            <div class="grid grid-cols-2 gap-4">
              <div>
                <div class="mb-2 font-bold">身份证正面</div>
                <el-form-item prop="legalIdFront">
                  <el-input v-model="formData.legalIdFront" placeholder="请输入身份证正面URL">
                    <template #append>
                      <el-button @click="previewImage(formData.legalIdFront)">预览</el-button>
                    </template>
                  </el-input>
                  <el-image
                    v-if="formData.legalIdFront"
                    :src="formData.legalIdFront"
                    :preview-src-list="[formData.legalIdFront]"
                    fit="contain"
                    style="width: 100%; max-height: 150px; margin-top: 8px;"
                  />
                </el-form-item>
              </div>
              <div>
                <div class="mb-2 font-bold">身份证背面</div>
                <el-form-item prop="legalIdBack">
                  <el-input v-model="formData.legalIdBack" placeholder="请输入身份证背面URL">
                    <template #append>
                      <el-button @click="previewImage(formData.legalIdBack)">预览</el-button>
                    </template>
                  </el-input>
                  <el-image
                    v-if="formData.legalIdBack"
                    :src="formData.legalIdBack"
                    :preview-src-list="[formData.legalIdBack]"
                    fit="contain"
                    style="width: 100%; max-height: 150px; margin-top: 8px;"
                  />
                </el-form-item>
              </div>
            </div>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="城市与数据类型">
          <!-- 城市选择 -->
          <el-form-item label="城市选择" prop="cityList">
            <div class="flex items-center mb-2">
              <el-button type="primary" size="small" @click="importExcelVisible = true" class="mr-2">
                <Icon icon="ep:upload" class="mr-1" />导入Excel
              </el-button>
              <span class="text-gray-500 text-sm">
                <Icon icon="ep:info-filled" class="mr-1" />
                支持Excel导入城市列表
              </span>
            </div>
            <el-select
              v-model="cityListArray"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="请选择或输入城市/省份"
              class="!w-full"
              :loading="loadingAreas"
              collapse-tags
              collapse-tags-tooltip
            >
              <el-option-group label="省份/自治区/直辖市">
                <el-option 
                  v-for="province in provinces" 
                  :key="province.value" 
                  :label="province.label" 
                  :value="province.value" 
                />
              </el-option-group>
              <el-option-group label="城市">
                <el-option 
                  v-for="city in cities" 
                  :key="city.value" 
                  :label="city.label" 
                  :value="city.value" 
                />
              </el-option-group>
            </el-select>
            <div class="text-gray-500 text-sm mt-1">
              <Icon icon="ep:info-filled" class="mr-1" />
              可以选择省份或城市，也可以直接输入城市名称，支持多选
            </div>
          </el-form-item>
          
          <!-- 数据类型选择 -->
          <el-form-item label="数据类型" prop="dataTypeList">
            <el-checkbox-group v-model="dataTypeArray" class="w-full">
              <el-checkbox :label="1">车抵贷</el-checkbox>
              <el-checkbox :label="2">信贷</el-checkbox>
              <el-checkbox :label="3">公积金</el-checkbox>
              <el-checkbox :label="4">企业</el-checkbox>
              <el-checkbox :label="5">消费</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          
          <div v-if="dataTypeArray.length > 0" class="mt-4">
            <div class="font-bold mb-2">已选数据类型：</div>
            <div>
              <el-tag 
                v-for="type in dataTypeArray" 
                :key="type" 
                class="mr-1 mb-1"
                :type="getDataTypeTagType(type)"
              >
                {{ getDataTypeLabel(type) }}
              </el-tag>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">提交</el-button>
      <el-button @click="dialogVisible = false">取消</el-button>
    </template>
  </Dialog>
  
  <!-- 图片预览 -->
  <el-dialog
    v-model="imageViewerVisible"
    title="图片预览"
    width="80%"
    destroy-on-close
    center
  >
    <div class="flex justify-center">
      <el-image
        v-if="previewImages.length > 0"
        :src="previewImages[0]"
        fit="contain"
        style="max-width: 100%; max-height: 70vh;"
      />
    </div>
  </el-dialog>
  
  <!-- Excel导入对话框-->
  <el-dialog
    v-model="importExcelVisible"
    title="导入城市列表"
    width="500px"
    destroy-on-close
  >
    <el-upload
      class="upload-demo"
      drag
      action="#"
      :auto-upload="false"
      :on-change="handleExcelChange"
      :show-file-list="true"
      accept=".xlsx,.xls"
    >
      <Icon icon="ep:upload-filled" class="text-3xl text-gray-400" />
      <div class="el-upload__text">
        将Excel文件拖到此处，或<em>点击上传</em>
      </div>
      <template #tip>
        <div class="el-upload__tip text-gray-500">
          请上传Excel文件，文件中的城市名称将被导入到城市列表中
        </div>
      </template>
    </el-upload>
    <div v-if="excelCities.length > 0" class="mt-4">
      <div class="font-bold mb-2">预览导入的城市：</div>
      <div class="max-h-40 overflow-y-auto border p-2 rounded">
        <el-tag 
          v-for="city in excelCities" 
          :key="city" 
          class="mr-1 mb-1"
        >
          {{ city }}
        </el-tag>
      </div>
    </div>
    <template #footer>
      <el-button @click="importExcelVisible = false">取消</el-button>
      <el-button type="primary" @click="confirmImportCities" :disabled="excelCities.length === 0">
        确认导入
      </el-button>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { UserAuthApi, UserAuthVO } from '@/api/weiyi/userauth'
import { getAreaTree } from '@/api/system/area'

// 如果项目中已经安装了xlsx库，使用下面的导入语句
// 如果没有安装，请先运行: npm install xlsx
import * as XLSX from 'xlsx'

/** 用户认证信息 表单 */
defineOptions({ name: 'UserAuthForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展开
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中（1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改

// 图片预览相关
const imageViewerVisible = ref(false)
const previewImages = ref<string[]>([])

// Excel导入相关
const importExcelVisible = ref(false)
const excelCities = ref<string[]>([])

// 省份和城市数据
const provinces = ref<any[]>([])
const cities = ref<any[]>([])
const loadingAreas = ref(false)

// 城市列表和数据类型数据
const cityListArray = ref<string[]>([])
const dataTypeArray = ref<number[]>([])

interface FormDataType {
  id?: number
  userId?: number
  companyName: string
  businessLicense: string
  bankName: string
  bankAccountName: string
  bankAccount: string
  legalName: string
  legalIdFront: string
  legalIdBack: string
  legalPhone: string
  status: number
  auditRemark?: string
  priceType: number
  fixedPrice: number
  minPrice: number
  maxPrice: number
  dailyDataLimit: number
  cityList: string
  dataType: string
  dataTypeList?: string
  authTime?: number
}

const formData = ref<FormDataType>({
  id: undefined,
  userId: undefined,
  companyName: '',
  businessLicense: '',
  bankName: '',
  bankAccountName: '',
  bankAccount: '',
  legalName: '',
  legalIdFront: '',
  legalIdBack: '',
  legalPhone: '',
  status: 0,
  auditRemark: undefined,
  priceType: 1,
  fixedPrice: 0,
  minPrice: 0,
  maxPrice: 0,
  dailyDataLimit: 0,
  cityList: '',
  dataType: '',
  dataTypeList: undefined,
  authTime: undefined
})

const formRules = reactive({
  userId: [{ required: true, message: '用户ID不能为空', trigger: 'blur' }],
  companyName: [{ required: true, message: '公司名称不能为空', trigger: 'blur' }],
  businessLicense: [{ required: true, message: '营业执照URL不能为空', trigger: 'blur' }],
  legalName: [{ required: true, message: '法人姓名不能为空', trigger: 'blur' }],
  legalIdFront: [{ required: true, message: '法人身份证正面URL不能为空', trigger: 'blur' }],
  legalIdBack: [{ required: true, message: '法人身份证背面URL不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '认证状态不能为空', trigger: 'change' }]
})

const formRef = ref() // 表单 Ref

// 加载省市数据
const loadAreaData = async () => {
  if (provinces.value.length > 0) return // 已加载过数据
  
  loadingAreas.value = true
  try {
    const res = await getAreaTree()
    if (res) {
      // 省份数据
      provinces.value = res.map(province => ({
        label: province.name,
        value: province.name,
        children: province.children || []
      }))
      
      // 城市数据
      const cityList: any[] = []
      provinces.value.forEach(province => {
        if (province.children && province.children.length > 0) {
          province.children.forEach((city: any) => {
            cityList.push({
              label: city.name,
              value: city.name,
              provinceId: province.id,
              provinceName: province.name
            })
          })
        }
      })
      cities.value = cityList
    }
  } catch (error) {
    console.error('获取地区数据失败:', error)
    message.error('获取地区数据失败')
  } finally {
    loadingAreas.value = false
  }
}

// 解析城市列表
const parseCityList = (cityListStr: string) => {
  try {
    return JSON.parse(cityListStr)
  } catch (e) {
    return []
  }
}

// 解析数据类型列表
const parseDataTypeList = (dataTypeListStr: string) => {
  try {
    return JSON.parse(dataTypeListStr)
  } catch (e) {
    return []
  }
}

// 获取数据类型标签
const getDataTypeLabel = (type: number | string) => {
  const typeMap = {
    '1': '车抵贷',
    '2': '信贷',
    '3': '公积金',
    '4': '企业',
    '5': '消费'
  }
  return typeMap[type] || `类型${type}`
}

// 获取数据类型标签样式
const getDataTypeTagType = (type: number | string) => {
  const typeMap = {
    '1': 'success',
    '2': 'primary',
    '3': 'warning',
    '4': 'danger',
    '5': 'info'
  }
  return typeMap[type] || ''
}

// 预览图片
const previewImage = (url: string | undefined) => {
  if (!url) {
    message.warning('图片URL为空，无法预览')
    return
  }
  previewImages.value = [url]
  imageViewerVisible.value = true
}

// 监听城市列表数组变化，同步到formData.cityList
watch(cityListArray, (newVal) => {
  formData.value.cityList = JSON.stringify(newVal)
}, { deep: true })

// 监听数据类型数组变化，同步到formData.dataType和formData.dataTypeList
watch(dataTypeArray, (newVal) => {
  formData.value.dataType = JSON.stringify(newVal)
  formData.value.dataTypeList = JSON.stringify(newVal)
}, { deep: true })

// Excel导入相关函数
const handleExcelChange = (file: any) => {
  if (!file.raw) {
    message.error('文件上传失败')
    return
  }
  
  const reader = new FileReader()
  reader.onload = (e) => {
    try {
      const data = e.target?.result
      const workbook = XLSX.read(data, { type: 'array' })
      const firstSheetName = workbook.SheetNames[0]
      const worksheet = workbook.Sheets[firstSheetName]
      const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 })
      
      // 提取城市名称
      const cities: string[] = []
      jsonData.forEach((row: any) => {
        if (Array.isArray(row)) {
          row.forEach((cell) => {
            if (cell && typeof cell === 'string') {
              const cityName = cell.trim()
              if (cityName && !cities.includes(cityName)) {
                cities.push(cityName)
              }
            }
          })
        } else if (row && typeof row === 'string') {
          const cityName = row.trim()
          if (cityName && !cities.includes(cityName)) {
            cities.push(cityName)
          }
        }
      })
      
      excelCities.value = cities
      if (cities.length === 0) {
        message.warning('未从Excel中提取到城市数据')
      }
    } catch (error) {
      console.error('解析Excel失败:', error)
      message.error('解析Excel失败，请检查文件格式')
    }
  }
  reader.readAsArrayBuffer(file.raw)
}

// 确认导入城市
const confirmImportCities = () => {
  if (excelCities.value.length === 0) {
    message.warning('没有可导入的城市数据')
    return
  }
  
  // 将Excel中的城市添加到选择框中
  excelCities.value.forEach(city => {
    if (!cityListArray.value.includes(city)) {
      cityListArray.value.push(city)
    }
  })
  
  message.success(`成功导入 ${excelCities.value.length} 个城市`)
  importExcelVisible.value = false
  excelCities.value = []
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  
  // 加载省市数据
  await loadAreaData()
  
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const detail = await UserAuthApi.getUserAuth(id)
      // 确保所有必需的字符串字段都有值
      formData.value = {
        ...formData.value,
        ...detail,
        companyName: detail.companyName || '',
        businessLicense: detail.businessLicense || '',
        bankName: detail.bankName || '',
        bankAccountName: detail.bankAccountName || '',
        bankAccount: detail.bankAccount || '',
        legalName: detail.legalName || '',
        legalIdFront: detail.legalIdFront || '',
        legalIdBack: detail.legalIdBack || '',
        legalPhone: detail.legalPhone || '',
        cityList: detail.cityList || '',
        dataType: detail.dataType || ''
      }
      
      // 初始化城市列表数组
      cityListArray.value = parseCityList(detail.cityList || '[]')
      
      // 初始化数据类型数组
      // 优先使用dataType字段，如果不存在则使用dataTypeList字段
      const dataTypeSource = detail.dataType || detail.dataTypeList || '[]'
      dataTypeArray.value = parseDataTypeList(dataTypeSource)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  
  // 提交请求
  formLoading.value = true
  try {
    // 确保城市列表和数据类型已同步到formData
    formData.value.cityList = JSON.stringify(cityListArray.value)
    formData.value.dataType = JSON.stringify(dataTypeArray.value)
    formData.value.dataTypeList = JSON.stringify(dataTypeArray.value)
    
    // 根据价格类型设置价格字段
    if (formData.value.priceType === 1) {
      // 清空浮动价格字段
      formData.value.minPrice = 0
      formData.value.maxPrice = 0
    } else if (formData.value.priceType === 2) {
      // 清空固定价格字段
      formData.value.fixedPrice = 0
    }
    
    // 如果是认证通过状态，但未设置认证时间，则设置为当前时间
    if (formData.value.status === 1 && !formData.value.authTime) {
      formData.value.authTime = new Date().getTime()
    }
    
    const data = formData.value as unknown as UserAuthVO
    if (formType.value === 'create') {
      await UserAuthApi.createUserAuth(data)
      message.success(t('common.createSuccess'))
    } else {
      await UserAuthApi.updateUserAuth(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    userId: undefined,
    companyName: '',
    businessLicense: '',
    bankName: '',
    bankAccountName: '',
    bankAccount: '',
    legalName: '',
    legalIdFront: '',
    legalIdBack: '',
    legalPhone: '',
    status: 0,
    auditRemark: undefined,
    priceType: 1,
    fixedPrice: 0,
    minPrice: 0,
    maxPrice: 0,
    dailyDataLimit: 0,
    cityList: '',
    dataType: '',
    dataTypeList: undefined,
    authTime: undefined
  }
  cityListArray.value = []
  dataTypeArray.value = []
  formRef.value?.resetFields()
}

// 初始化
onMounted(() => {
  loadAreaData() // 加载省市数据
})
</script>

<style lang="scss" scoped>
.image-error {
  display: flex;
  width: 100%;
  height: 100%;
  font-size: 20px;
  color: #909399;
  background-color: #f5f7fa;
  justify-content: center;
  align-items: center;
}

.cursor-pointer {
  cursor: pointer;
  transition: all 0.3s;
  
  &:hover {
    transform: scale(1.05);
  }
}

.text-xs {
  font-size: 12px;
}
</style>
